<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermission(1, 0)">添加权限</el-button>
        </div>

        <el-table border :data="permissionList" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button v-if="scope.row.type === 1" type="text" @click="addPermission(2, scope.row.id)">添加</el-button>
              <el-button type="text" @click="huiTian(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="delFn(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 放置一个弹层 用来编辑新增节点 -->
        <el-dialog :title="isEdit? '编辑权限点' : '新增权限点'" :visible="showDialog" @close="btnCancel">
          <!-- 表单 -->
          <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
            <el-form-item label="权限名称" prop="name">
              <el-input v-model="formData.name" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限标识" prop="code">
              <el-input v-model="formData.code" style="width:90%" />
            </el-form-item>
            <el-form-item label="权限描述">
              <el-input v-model="formData.description" style="width:90%" />
            </el-form-item>
            <el-form-item label="开启">
              <el-switch
                v-model="formData.enVisible"
                active-value="1"
                inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" type="primary" @click="queRen">确定</el-button>
              <el-button size="small" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>

      </el-card>
    </div>
  </div>
</template>

<script>
// 导入API
import { getPermissionListAPI, addPermissionAPI, getPermissionDetail, updatePermissionAPI, delPermissionAPI } from '@/api/permission'
// 导入树形数据
import { tranListToTreeData } from '@/utils/index'
export default {
  name: 'Quanxian',
  data() {
    // 校验权限名称
    const validName = (rule, value, callback) => {
      // 添加时的校验： 名字不能取子元素的名字
      let existNameList = this.originList.filter(item => item.pid === this.formData.pid)
      if (this.isEdit) {
        // 编辑时的校验： 名字不能取兄弟（排除自己）的名字
        // 找兄弟，排除自己
        existNameList = this.originList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id)
      }
      existNameList.map(it => it.name).includes(value)
        ? callback(new Error(value + '已经占用'))
        : callback()
    }

    // 校验权限标识
    const validCode = (rule, value, callback) => {
      // 添加时的校验：code不能重复
      let existCodeList = this.originList
      if (this.isEdit) {
        // 编辑时的校验: code能取自己
        existCodeList = this.originList.filter(item => item.id !== this.formData.id)
      }
      existCodeList.map(it => it.code).includes(value)
        ? callback(new Error(value + '已经占用'))
        : callback()
    }
    return {
      permissionList: [], // 权限列表
      showDialog: false, // 弹窗隐藏显示
      formData: {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      },
      rules: {
        name: [{ required: true, message: '权限名称不能为空', trigger: 'blur' }, { validator: validName, trigger: 'blur' }],
        code: [{ required: true, message: '权限标识不能为空', trigger: 'blur' }, { validator: validCode, trigger: 'blur' }]
      },
      isEdit: false, // 是否为编辑状态
      originList: [] // 在做校验时需要用到的数据
    }
  },
  created() {
    // 获取权限列表
    this.getPermissionList()
  },
  methods: {
    // 删除按钮
    async delFn(row) {
      if (row.children) return this.$message.info('里面还有子权限')
      const confirmRes = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmRes)
      if (confirmRes === 'cancel') return this.$message.info('已取消')
      const res = await delPermissionAPI(row.id)
      this.$message.success(res.message)
      // 获取权限列表
      this.getPermissionList()
    },

    // 确认添加/编辑按钮
    queRen() {
      // 兜底校验
      this.$refs.perForm.validate((valid) => {
        if (!valid) return
        this.isEdit ? this.binajiAPI() : this.tianjiaAPI()
      })
    },

    // 发起添加请求
    async tianjiaAPI() {
      const res = await addPermissionAPI(this.formData)
      // 提示
      this.$message.success(res.message)
      // 弹窗关闭
      this.showDialog = false
      // 再次获取权限列表
      this.getPermissionList()
    },

    // 发起编辑请求
    async binajiAPI() {
      const res = await updatePermissionAPI(this.formData)
      // 提示
      this.$message.success(res.message)
      // 弹窗关闭
      this.showDialog = false
      // 再次获取权限列表
      this.getPermissionList()
    },

    // 点击编辑 数据回填
    async huiTian(id) {
      this.isEdit = true // 编辑状态
      const res = await getPermissionDetail(id)
      // console.log(res)
      this.formData = res.data // 数据赋值
      this.showDialog = true // 开启弹窗
    },

    // 两个添加按钮
    addPermission(type, pid) {
      this.showDialog = true // 开启弹窗

      this.formData.type = type // 分辨是哪个添加
      this.formData.pid = pid // 分辨是哪个添加
    },

    // 弹窗关闭时
    btnCancel() {
      this.showDialog = false
      this.isEdit = false
      this.formData = {
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        enVisible: '0', // 开启
        pid: '', // 添加到哪个节点下
        type: '' // 类型
      }
      // 重置表单
      this.$refs.perForm.resetFields()
    },

    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionListAPI()
      // console.log(res)
      this.originList = res.data.map(({ id, pid, name, code }) => ({ id, pid, name: name.trim(), code }))
      // 调用树形数据
      this.permissionList = tranListToTreeData(res.data, '0')
    }
  }
}
</script>

<style lang="scss" scoped></style>
